#!/bin/bash

HOSTNAME=$1
DOMAIN=$2
LOCALDOMAIN=$3
if [ -z $HOSTNAME ]; then
    echo "Expected hostname argument"
    exit 1
fi
if [ -z $DOMAIN ]; then
    echo "Expected domain argument"
    exit 1
fi
FQDN=$HOSTNAME"."$DOMAIN

SANDATA="DNS.1:"$FQDN
if [ ! -z $LOCALDOMAIN ]; then
    SANDATA="DNS.1:"$FQDN", DNS.2:"$LOCALDOMAIN
fi
export SAN=$SANDATA
export DOMAIN=$DOMAIN

rm -f intermediate/private/ecdsa.$FQDN.key.pem
rm -f intermediate/private/rsa.$FQDN.key.pem
rm intermediate/csr/ecdsa.$FQDN.csr.pem
rm intermediate/csr/rsa.$FQDN.csr.pem
rm intermediate/certs/ecdsa.$FQDN.cert.pem
rm intermediate/certs/rsa.$FQDN.cert.pem

# Create ECDSA key
openssl ecparam -name secp256r1 -genkey -noout -out intermediate/private/ecdsa.$FQDN.key.pem
chmod 400 intermediate/private/ecdsa.$FQDN.key.pem

# Create RSA Key
openssl genrsa -out intermediate/private/rsa.$FQDN.key.pem 2048
chmod 400 intermediate/private/rsa.$FQDN.key.pem

# Create ECDSA CSR
openssl req -config intermediate/openssl.cnf -key intermediate/private/ecdsa.$FQDN.key.pem -new -sha256 -out intermediate/csr/ecdsa.$FQDN.csr.pem -subj "/C=GB/ST=England/O=NMOS Testing Ltd/CN=$FQDN"

# Create RSA CSR
openssl req -config intermediate/openssl.cnf -key intermediate/private/rsa.$FQDN.key.pem -new -sha256 -out intermediate/csr/rsa.$FQDN.csr.pem -subj "/C=GB/ST=England/O=NMOS Testing Ltd/CN=$FQDN"

# Sign ECDSA CSR
openssl ca -batch -config intermediate/openssl.cnf -extensions server_cert -days 18250 -notext -md sha256 -in intermediate/csr/ecdsa.$FQDN.csr.pem -out intermediate/certs/ecdsa.$FQDN.cert.pem
cat intermediate/certs/ecdsa.$FQDN.cert.pem intermediate/certs/ca-chain.cert.pem > intermediate/certs/ecdsa.$FQDN.cert.chain.pem
openssl pkcs12 -passout pass: -export -out intermediate/certs/ecdsa.$FQDN.cert.pfx -inkey intermediate/private/ecdsa.$FQDN.key.pem -in intermediate/certs/ecdsa.$FQDN.cert.pem
openssl pkcs12 -passout pass: -export -out intermediate/certs/ecdsa.$FQDN.cert.chain.pfx -inkey intermediate/private/ecdsa.$FQDN.key.pem -in intermediate/certs/ecdsa.$FQDN.cert.pem -certfile intermediate/certs/ca-chain.cert.pem

# Sign RSA CSR
openssl ca -batch -config intermediate/openssl.cnf -extensions server_cert -days 18250 -notext -md sha256 -in intermediate/csr/rsa.$FQDN.csr.pem -out intermediate/certs/rsa.$FQDN.cert.pem
cat intermediate/certs/rsa.$FQDN.cert.pem intermediate/certs/ca-chain.cert.pem > intermediate/certs/rsa.$FQDN.cert.chain.pem
openssl pkcs12 -passout pass: -export -out intermediate/certs/rsa.$FQDN.cert.pfx -inkey intermediate/private/rsa.$FQDN.key.pem -in intermediate/certs/rsa.$FQDN.cert.pem
openssl pkcs12 -passout pass: -export -out intermediate/certs/rsa.$FQDN.cert.chain.pfx -inkey intermediate/private/rsa.$FQDN.key.pem -in intermediate/certs/rsa.$FQDN.cert.pem -certfile intermediate/certs/ca-chain.cert.pem
